var layer = layui.layer, //弹层
    table = layui.table, //表格
    form = layui.form,
    $ = layui.jquery,
    changeList=[],
    laydate = layui.laydate,
    indexs = 0,
    checkboxs =false;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});



//报关明细集合
let getBillDeclareProductInfoList=[];
let getBillDeclareInfoList=[];
table.render({
    elem: '#mains'
    ,data:getBillDeclareInfoList
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field:'invoiceCode', title:'报关发票号码',sort:true}
        ,{field:'contractCode', title:'合同编号',sort:true}
        ,{field:'manufacturerName', title:'厂商名称',sort:true}
        ,{field:'companyName', title:'签约公司',sort:true}
        ,{field:'declarationStr', title:'报关日期',sort:true}
        ,{field:'shippingStr', title:'出运日期',sort:true}
        ,{field:'priceTerm', title:'价格术语',sort:true}
        ,{field:'salesmanName', title:'业务员',sort:true}
    ]]
    ,id: 'mainstableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#product'
            ,data:getBillDeclareProductInfoList
            ,url:"billing/getBillDeclareProductInfoListByPage"
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'}
                ,{field: 'stockCode', width: 120, title: '采购单号', sort: true}
                ,{field:'goodsCode', title:'产品编码', width: 120, sort : true}
                ,{field:'specCode', title:'规格编码',  width: 120,sort : true}
                ,{field:'goodsSpec', title:'规格说明',  width: 120,sort : true}
                ,{field:'goodsCname', title:'中文名称', width: 120, sort : true}
                ,{field:'goodsEname', title:'英文名称',  width: 120,sort : true}
                ,{field: 'goodsCdesc', title: '中文描述',  width: 120,sort: true}
                ,{field: 'goodsEdesc', title: '英文描述', width: 120, sort: true}
                ,{field:'goodsNum', title:'数量', width: 120, sort : true}//此数量已在下方更改为 canBillingAmount
                ,{field:'goodsUnit', title:'单位', width: 120, sort : true}
                ,{field:'lastAmount', title:'剩余数量', width: 120, sort : true}
                ,{field:'declarePrice', title:'报关单价', width: 120, sort:true}
                ,{field:'totalPrice', title:'报关金额小计', width: 130, sort:true}
                ,{field:'stockPrice', title:'成本价', width: 120, sort:true}
                ,{field:'costSubtotal', title:'成本小计', width: 120, sort:true}
                ,{field: 'saleContractCode', width: 120, title: '销售合同号', sort: true},
                ,{field: 'canBillingAmount', hide:true},


            ]]
            ,id: 'producttableid'
            ,where: {
                declareId:res.data.length == 0 ? "":res.data[0].declareId,      //默认第一条信息，数据为空则declareId为空
                manufacturerName:res.data.length==0?"":res.data[0].manufacturerName,
                invoiceCode:res.data.length==0?"":res.data[0].invoiceCode,
            }
            ,height: 400
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });

    }
});
//提交查询条件
form.on('submit(submitform)', function(data){
    table.reload('mainstableid', {
        page: {
            limit:10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
        ,url:'billing/getBillDeclareInfoListByPage'
    }, 'data');
    return false;
});

//监听复选框主表
table.on('checkbox(mainstable)', function (data) {
    if(data.type == 'all'){
        //allDataOperation(data);
    }else if(data.type == 'one'){
        oneDataOperation(data);
    }
});
//复选框主表单选
function oneDataOperation(data) {
    let declareId = data.data.declareId;
    let manufacturerName= data.data.manufacturerName;
    let invoiceCode= data.data.invoiceCode;
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            declareId:declareId,
            manufacturerName:manufacturerName,
            invoiceCode:invoiceCode
        },
        done: function (res, curr, count) {
            var child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){
                for(var i = 0; i < res.data.length; i++){
                    changeList.push(res.data[i]);
                }
            }else{
                if(changeList.length > 0){
                    for(var i = 0; i < res.data.length; i++){
                        deleteData(res.data[i]);
                    }
                }
            }
            form.render('checkbox');
        }
    }, 'data');
}
//删除元素
function deleteData(data){
    let declareId = data.declareId;
    let declareProductId = data.declareProductId;
    for(var j = 0; j < changeList.length; j++){
        if (changeList[j].declareId == declareId && changeList[j].declareProductId == declareProductId) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}
//监听复选框子表
table.on('checkbox(producttable)', function (obj) {
    if ( obj.type == 'one' ) {
        if (obj.checked) {
            changeList.push(obj.data);
        } else {
            for (let index in changeList) {
                if (changeList[index].declareId == obj.data.declareId && changeList[index].declareProductId == obj.data.declareProductId) {
                    changeList.splice(index,1);
                }
            }
        }
    } else if (obj.type == 'all') {
        // 子表数全选待处理

    }
    form.render('checkbox');
});
//主表单击行事件
table.on('row(mainstable)', function (obj) {
    let declareId = obj.data.declareId;
    let manufacturerName=obj.data.manufacturerName;
    let invoiceCode=obj.data.invoiceCode;
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            declareId:declareId,
            manufacturerName:manufacturerName,
            invoiceCode:invoiceCode
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j].declareId == res.data[i].declareId &&  changeList[j].declareProductId == res.data[i].declareProductId) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
        done: function (res, curr, count) {

        }
    }, 'data');
});

//用户选择数据
$("#choose").on("click",function () {
    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        let oldData =  parent.table.cache["moaidetailtableid"];
        $.each(changeList, function (index, value) {
            //剔除重复数据
            let flag = true;
            if(oldData.length > 0){
                for(var i = 0; i < oldData.length; i++){
                    let sameFlag = oldData[i].declareProductId == changeList[index].declareProductId && oldData[i].declareId == changeList[index].declareId;
                    if(sameFlag){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag){
                //临时id
                changeList[index]['tempId']=Number(Math.random().toString().substr(3,3) + Date.now()).toString(36)+(index+1);
                //开票单价=采购单价
                changeList[index]['invoiceUnitPrice'] = changeList[index].stockPrice;
                //采购单价
                changeList[index]['purchaseUnitPrice']= changeList[index].stockPrice;
                //成本单价
                changeList[index]['unitCost'] = changeList[index].costUnitPrice;
                //报关发票号码
                changeList[index]['declarationInvoiceCode'] =changeList[index].invoiceCode;
                //默认的开票小计=数量*采购单价
                changeList[index]['invoiceSubtotal'] = Number(changeList[index].stockPrice)*Number(changeList[index].goodsNum);
                //可以开票的数量
                changeList[index]['goodsNum'] =changeList[index].canBillingAmount
                //添加判断字段，修改时使用
                changeList[index]['updateTemp'] = 1;
                //开票单据来源（1导入报关，2导入采购，3导入外销，4导入结汇）
                changeList[index]['invoiceType'] = 1;
                //不存在重复数据,添加数据
                oldData.push(changeList[index]);

            }
        });

        parent.table.reload('moaidetailtableid', {data:oldData});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },)
    }
})
$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})
